package com.example.moshudriver.fragment;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Set;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import com.BeeFramework.Utils.TimeUtil;
import com.BeeFramework.Utils.Utils;
import com.BeeFramework.model.BusinessResponse;
import com.BeeFramework.view.RoundedWebImageView;
import com.BeeFramework.view.ToastView;
import com.sgr.dykdriver.R;
import com.example.moshudriver.activity.C0_ServiceListActivity;
import com.example.moshudriver.activity.D1_OrderActivity;
import com.example.moshudriver.activity.SlidingActivity;
import com.example.moshudriver.jpush.ExampleUtil;
import com.example.moshudriver.model.OrderInfoModel;
import com.example.moshudriver.model.PublishedOrderListModel;
import com.example.moshudriver.model.UserBalanceModel;
import com.example.moshudriver.model.UserModel;
import com.example.moshudriver.protocol.ApiInterface;
import com.example.moshudriver.protocol.USER;
import com.example.moshudriver.protocol.orderacceptResponse;
import com.example.moshudriver.protocol.orderlistpublishedResponse;
import com.example.moshudriver.protocol.userprofileResponse;
import com.example.moshudriver.tools.LocationManager;
import com.example.moshudriver.tools.MessageConstant;
import com.example.moshudriver.tools.O2OMobile;
import com.example.moshudriver.tools.O2OMobileAppConst;
import com.example.moshudriver.tools.SESSION;
import com.example.moshudriver.view.SettingItemView;
import com.external.androidquery.callback.AjaxStatus;
import com.external.eventbus.EventBus;
import com.external.maxwin.view.IXListViewListener;
import com.external.maxwin.view.XListView;
import com.nostra13.universalimageloader.core.ImageLoader;

public class A1_HomeFragment extends Fragment implements OnClickListener,
		BusinessResponse, IXListViewListener {
	// private ImageView A0_bar_bell;
	private ImageView mMenu, A0_back;
	private Dialog dialog;
	private RoundedWebImageView mAvarta;
	private TextView A0_near_order, mName, mOrder_finish_rate, mOrderNum, tv_end, mPrice,
			tv_create_time, tv_select_model, tv_listen_order, tv_back_car,
			tv_start, mCommentGoodRate, mBalance;

	// private LinearLayout A0_linearLayout_bottom;
	private View view;
	private RelativeLayout ly_jpull_order;
	private String mOrderId;
	// private TextView a0_order, a0_text_test;
	// public static boolean isForeground = false;// 是否在后台
	public static boolean isHasOrder = false;// 是否有订单
	public static boolean isWork = true;// 是否出车
	public static boolean isAccept = true;// 是否接单\ true 为可以接单
	public static boolean isDone = false;// 订单是否处理
	public static int isfinsh = -1;// 订单是否处理  ==0不能接单
	private Boolean isOpenModel = false;// 模式是否打开
	private SettingItemView siv_real_time, siv_appiont, siv_all;
	private boolean is_accept_real_time;
	private boolean is_accept_appiont;
	private boolean is_accept_all;
	// public static boolean isFirstAccept = true;// 是否接单\
	// private int orderCount = 1;// 控制订单数量

	public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
	public static final String KEY_TITLE = "title";
	public static final String KEY_MESSAGE = "message";
	public static final String KEY_EXTRAS = "extras";
	public static String balance;
	// private TextView tv_listen_order;
	// private XListView A0_orderlist;
	private String messge;
	private USER mUser;
	private XListView a0_listview;
	private View a0_home;
	private ImageView iv_listen_order;
	private ImageView starOne, starTwo, starThree, starFour, starFive;

	private SharedPreferences mShared, mShared1, mShared2;
	private SharedPreferences.Editor mEditor, mEditor1;
	private UserBalanceModel mUserBalance;
	PublishedOrderListModel orderModel;
	private int mUserId;
	private UserModel mUserModel;
	protected ImageLoader mImageLoader = ImageLoader.getInstance();
	private MessageReceiver mMessageReceiver;
	private OrderInfoModel mOrderInfoModel;
	private static int orderId;
	private Button btn_change_next_order;
	ImageView a1_img_type;
	public static ArrayList<String> listId = new ArrayList<String>();
	private ArrayList<ImageView> starList;
	private RelativeLayout ll_layout;
	private RelativeLayout rl_main;
	// private int receiveRealTime=1;
	// private int receiveAppiont=2;
	private int receiveType = 3;// 1为实时订单，2为预约订单,3为全部订单

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.a0_home_pre, null);
		// 初始化极光推送
		initJPush();
		// 初始化媒体
		player = MediaPlayer.create(getActivity(), R.raw.alert_order2);
		// ===========调起系统的震动================
		vibrator = (Vibrator) getActivity().getSystemService(
				Context.VIBRATOR_SERVICE);

		view.setOnClickListener(null);
		mShared = getActivity().getSharedPreferences(
				O2OMobileAppConst.USERINFO, 0);
		mShared1 = getActivity().getSharedPreferences(
				O2OMobileAppConst.LOCATION_CHARGE, 0);// 位置计费表
		// --------------------------
		mShared2 = getActivity().getSharedPreferences(O2OMobileAppConst.MODEL,
				0);// 模式
		editor = mShared2.edit();

		is_accept_real_time = mShared2.getBoolean("is_accept_real_time", true);
		is_accept_appiont = mShared2.getBoolean("is_accept_appiont", true);
		is_accept_all = mShared2.getBoolean("is_accept_all", true);
		// --------------------------
		mEditor = mShared.edit();
		mEditor1 = mShared1.edit();
		mUserId = mShared.getInt("uid", 0);
		
		int uid = mShared.getInt("uid", 0);
		setAlias(String.valueOf(uid));// 绑定用户id到极光的服务器上（设置别名）
	
		initView();
		mUserModel = new UserModel(getActivity());
		mUserModel.addResponseListener(this);
		mOrderInfoModel = new OrderInfoModel(getActivity());
		mOrderInfoModel.addResponseListener(this);
		orderModel = new PublishedOrderListModel(getActivity());
		orderModel.addResponseListener(this);
		orderModel.isAccept();// 判断司机是否可以接单
		mUserBalance = new UserBalanceModel(getActivity());
		mUserBalance.addResponseListener(this);
		// mUserBalance.getProfile(mUserId);
		mUserBalance.getProfile_driver();
		if (mUserId == SESSION.getInstance().uid) {
			mUserBalance.get();
		}

		// 不同状态下，不同动作的动画
		int isopen = mShared1.getInt("isopen", 1);
		if (isopen == 1) {
			stateAction();// 听单
		} else {
			// 城市未開通的时候，不接受推送订单

			// 无订单
			isHasOrder = false;
			// isForeground = false;
			// 不接受订单
			isAccept = false;
			// 如果处于工作状态
			isWork = false;

			// 设置刷新和收车不可见。清除动画，设置为出车
			showOut();

		}

		if (!EventBus.getDefault().isregister(this)) {
			EventBus.getDefault().register(this);
		}
		LocationManager.getInstance().refreshLocation();//更新地址
		return view;
	}

	/**
	 * 初始化极光推送
	 */
	private void initJPush() {
		// TODO Auto-generated method stub
		JPushInterface.init(getActivity());
		registerMessageReceiver();
	}

	/**
	 * 加载听单动画
	 */
	private void stateAction() {

		iv_listen_order.setBackgroundResource(R.drawable.common_search_loading);
		Animation operatingAnim = AnimationUtils.loadAnimation(getActivity(),
				R.anim.wait_order);
		LinearInterpolator lin = new LinearInterpolator();
		operatingAnim.setInterpolator(lin);
		if (operatingAnim != null) {
			iv_listen_order.startAnimation(operatingAnim);
			tv_listen_order.setText("听单");
		}
	}

	private void initView() {

		a0_listview = (XListView) view.findViewById(R.id.a0_listview);
		A0_near_order=(TextView)view.findViewById(R.id.A0_near_order);
		a0_home = LayoutInflater.from(getActivity()).inflate(R.layout.a0_home,
				null);
//		 a0_home = view.inflate(getActivity(), R.layout.a0_home, null);
		a0_listview.addHeaderView(a0_home);
		a0_listview.setPullLoadEnable(false);
		a0_listview.loadMoreHide();
		a0_listview.setRefreshTime();
		a0_listview.setXListViewListener(this, 1);
		a0_listview.setAdapter(null);
		a1_img_type = (ImageView) view.findViewById(R.id.a1_img_type);

		rl_main = (RelativeLayout) view.findViewById(R.id.rl_main);
		ll_layout = (RelativeLayout) view.findViewById(R.id.ll_model);
		// Button btn_model = (Button) view.findViewById(R.id.btn_model);
		// 实时

		siv_real_time = (SettingItemView) view.findViewById(R.id.siv_real_time);
		siv_real_time.tv_title.setText("是否接受实时订单");
		// 预约
		siv_appiont = (SettingItemView) view.findViewById(R.id.siv_appiont);
		siv_appiont.tv_title.setText("是否接受预约订单");
		// 全部
		siv_all = (SettingItemView) view.findViewById(R.id.siv_all);
		siv_all.tv_title.setText("是否接受全部订单");
		// 检查模式的状态
		checkModeStatus();

		iv_listen_order = (ImageView) view.findViewById(R.id.iv_listen_order);
		// A0_bar_bell = (ImageView) view.findViewById(R.id.A0_bar_bell);
		mMenu = (ImageView) view.findViewById(R.id.home_menu);
		A0_back = (ImageView) view.findViewById(R.id.A0_back);
		// 头像
		mAvarta = (RoundedWebImageView) view.findViewById(R.id.iv_avarta);
		// 司机名字
		mName = (TextView) view.findViewById(R.id.a0_driver_name);
		// 订单数
		mOrderNum = (TextView) view.findViewById(R.id.tv_order_num);
		// 订单完成率
		mOrder_finish_rate = (TextView) view
				.findViewById(R.id.tv_order_finish_rate);
		// 好评率
		mCommentGoodRate = (TextView) view
				.findViewById(R.id.tv_comment_goodrate);
		// 等级
		starOne = (ImageView) view.findViewById(R.id.f8_star_one);
		starTwo = (ImageView) view.findViewById(R.id.f8_star_two);
		starThree = (ImageView) view.findViewById(R.id.f8_star_three);
		starFour = (ImageView) view.findViewById(R.id.f8_star_four);
		starFive = (ImageView) view.findViewById(R.id.f8_star_five);
		starList = new ArrayList<ImageView>();
		starList.add(starOne);
		starList.add(starTwo);
		starList.add(starThree);
		starList.add(starFour);
		starList.add(starFive);

		// 余额
		mBalance = (TextView) view.findViewById(R.id.a0_tv_get_balance);
		// 换一个订单
		btn_change_next_order = (Button) view
				.findViewById(R.id.btn_change_next_order);

		ly_jpull_order = (RelativeLayout) view
				.findViewById(R.id.ly_jpull_order);
		ly_jpull_order.setVisibility(View.GONE);
		// tv_time.setText(TimeUtil.timeAgo(String.valueOf(System
		// .currentTimeMillis())));
		// 起点
		tv_start = (TextView) view.findViewById(R.id.tv_name_start);
		// 终点
		tv_end = (TextView) view.findViewById(R.id.tv_name_end);
		// 订单创建时间
		tv_create_time = (TextView) view.findViewById(R.id.a0_create_time);
		// 估计价格
		mPrice = (TextView) view.findViewById(R.id.a0_price);

		// 选择模式
		tv_select_model = (TextView) view.findViewById(R.id.tv_select_model);
		// 听单
		tv_listen_order = (TextView) view.findViewById(R.id.tv_listen_order);
		// 收车
		tv_back_car = (TextView) view.findViewById(R.id.tv_back_car);
		A0_near_order.setOnClickListener(this);

		btn_change_next_order.setOnClickListener(this);
		tv_select_model.setOnClickListener(this);
		tv_listen_order.setOnClickListener(this);
		tv_back_car.setOnClickListener(this);
		mMenu.setOnClickListener(this);
		// A0_bar_bell.setOnClickListener(this);
		A0_back.setOnClickListener(this);
		siv_real_time.setOnClickListener(this);
		siv_appiont.setOnClickListener(this);
		siv_all.setOnClickListener(this);
		// btn_real_time.setOnClickListener(this);
		// btn_appoint.setOnClickListener(this);
		// btn_all.setOnClickListener(this);

	}

	/**
	 * 检查模式的状态
	 */
	private void checkModeStatus() {
		if (is_accept_real_time) {
			// 接受实时订单已经开启
			siv_real_time.setChecked(true);
			siv_real_time.setDesc("接受实时订单已经开启");
		} else {
			// 接受实时订单已经关闭
			siv_real_time.setChecked(false);
			siv_real_time.setDesc("接受实时订单已经关闭");
		}
		if (is_accept_appiont) {
			// 接受预约订单已经开启
			siv_appiont.setChecked(true);
			siv_appiont.setDesc("接受预约订单已经开启");
		} else {
			// 接受预约订单已经关闭
			siv_appiont.setChecked(false);
			siv_appiont.setDesc("接受预约订单已经关闭");
		}

		if (is_accept_all) {
			// 接受全部订单已经开启
			siv_all.setChecked(true);
			siv_real_time.setChecked(true);
			siv_appiont.setChecked(true);
			siv_real_time.setClickable(false);
			siv_appiont.setClickable(false);
			siv_all.setDesc("接受全部订单已经开启");
		} else {
			// 接受全部订单已经关闭
			siv_all.setChecked(false);
			siv_real_time.setClickable(true);
			siv_appiont.setClickable(true);
			siv_all.setDesc("接受全部订单已经关闭");
		}

	}

	@Override
	public void onDestroy() {
		getActivity().unregisterReceiver(mMessageReceiver);
		super.onDestroy();
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();

	}

	@Override
	public void onPause() {
		// isForeground = false;
		super.onPause();
	}

	@Override
	public void onResume() {
		if (isWork) {
			// 保持准备出车的状态
			// clearOrder();
			isAccept = true;
		} else {
			// 保持收车的状态
			showOut();

		}
		if (D1_OrderActivity.isfinsh_order) {// 当订单完成了，那么就可以更新界面
			D1_OrderActivity.isfinsh_order = false;
			if (mUserBalance != null) {
				mUserBalance.getProfile_driver();
				mUserBalance.get();
			}

			loadSaveOrder();
		} else {

		}

		super.onResume();

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		
		case R.id.A0_near_order:
			Intent intent = new Intent(getActivity(), C0_ServiceListActivity.class);
//			intent.putExtra(D1_OrderActivity.ORDER_ID, orderId);
			startActivity(intent);
			getActivity().overridePendingTransition(R.anim.push_right_in,
					R.anim.push_right_out);
			break;
		
	/*	*/
		
		
		case R.id.home_menu:
			((SlidingActivity) getActivity()).showLeft();
			break;
		case R.id.siv_real_time:
			// 判断是否有选中
			// 已经打开实时订单了
			if (siv_real_time.isChecked()) {
				siv_real_time.setChecked(false);
				siv_real_time.setDesc("接受实时订单已经关闭");
				editor.putBoolean("is_accept_real_time", false);
				if (is_accept_all) {
					editor.putBoolean("is_accept_all", false);
				}
				// 清除实时订单
				receiveType = 5;

			} else {
				// 没有打开实时订单
				siv_real_time.setChecked(true);
				siv_real_time.setDesc("接受实时订单已经开启");
				editor.putBoolean("is_accept_real_time", true);
				// 接受实时订单
				receiveType=1;
//				acceptRealTimeOrder();
				if (is_accept_appiont) {
					editor.putBoolean("is_accept_all", true);
				}

			}
			editor.commit();
			is_accept_real_time = mShared2.getBoolean("is_accept_real_time",
					false);
			is_accept_appiont = mShared2.getBoolean("is_accept_appiont", false);
			System.out.println("is_accept_real_time:" + is_accept_real_time);
			System.out.println("is_accept_appiont:" + is_accept_appiont);
			if (is_accept_real_time && is_accept_appiont) {
				siv_all.setChecked(true);
				siv_all.setDesc("接受全部订单已经开启");
				// 接受所有订单
				receiveType=3;
			}
			if (!is_accept_real_time || !is_accept_appiont) {
				siv_all.setChecked(false);
				siv_all.setDesc("接受全部订单已经关闭");
			}

			break;
		case R.id.siv_appiont:

			// 判断是否有选中
			// 已经打开预约订单了
			if (siv_appiont.isChecked()) {
				siv_appiont.setChecked(false);
				siv_appiont.setDesc("接受预约订单已经关闭");
				editor.putBoolean("is_accept_appiont", false);
				// 不接受预约订单
				receiveType = 6;
				if (is_accept_all) {
					editor.putBoolean("is_accept_all", false);
				}

			} else {
				// 没有打开预约订单
				siv_appiont.setChecked(true);
				siv_appiont.setDesc("接受预约订单已经开启");
				editor.putBoolean("is_accept_appiont", true);
				// 接受预约订单
				receiveType=2;
//				acceptAppointOrder();
				if (is_accept_real_time) {
					editor.putBoolean("is_accept_all", true);
					
					// acceptAllOrder();
				}

			}
			editor.commit();
			is_accept_real_time = mShared2.getBoolean("is_accept_real_time",
					false);
			is_accept_appiont = mShared2.getBoolean("is_accept_appiont", false);
			System.out.println("is_accept_real_time:" + is_accept_real_time);
			System.out.println("is_accept_appiont:" + is_accept_appiont);
			// editor.putBoolean("is_accept_all", false);
			if (is_accept_real_time && is_accept_appiont) {
				siv_all.setChecked(true);
				siv_all.setDesc("接受全部订单已经开启");
				// editor.putBoolean("is_accept_all", true);
				// 接受所有订单
				receiveType=3;
			}
			if (!is_accept_real_time || !is_accept_appiont) {
				siv_all.setChecked(false);
				siv_all.setDesc("接受全部订单已经关闭");
			}

			break;
		case R.id.siv_all:

			// 判断是否有选中
			// 已经打开接受全部订单了
			if (siv_all.isChecked()) {
				siv_all.setChecked(false);
				siv_real_time.setChecked(false);
				siv_appiont.setChecked(false);
				siv_all.setDesc("接受全部订单已经关闭");
				siv_real_time.setDesc("接受实时订单已经关闭");
				siv_appiont.setDesc("接受预约订单已经关闭");
				siv_all.setDesc("接受全部订单已经关闭");
				editor.putBoolean("is_accept_appiont", false);
				editor.putBoolean("is_accept_real_time", false);
				editor.putBoolean("is_accept_all", false);
				receiveType=4;

			} else {
				// 没有打开接受全部订单
				siv_all.setChecked(true);
				siv_real_time.setChecked(true);
				siv_appiont.setChecked(true);
				siv_real_time.setDesc("接受实时订单已经开启");
				siv_appiont.setDesc("接受预约订单已经开启");
				siv_all.setDesc("接受全部订单已经开启");
				editor.putBoolean("is_accept_appiont", true);
				editor.putBoolean("is_accept_real_time", true);
				editor.putBoolean("is_accept_all", true);
				receiveType=3;
			}
			editor.commit();
			// is_accept_real_time = mShared2.getBoolean("is_accept_real_time",
			// false);
			// is_accept_appiont = mShared2.getBoolean("is_accept_appiont",
			// false);
			// System.out.println("is_accept_real_time:" + is_accept_real_time);
			// System.out.println("is_accept_appiont:" + is_accept_appiont);

			break;
		case R.id.btn_change_next_order:// 取消按钮

			loadSaveOrder();
			break;
		case R.id.tv_select_model:// 模式

			// TODO Auto-generated method stub
			if (!isOpenModel) {
				isOpenModel = true;
				ll_layout.setVisibility(View.VISIBLE);
				rl_main.setVisibility(View.GONE);
				tv_select_model.setText("完成");
//				 getActivity().overridePendingTransition(R.anim.push_right_out,
//				 R.anim.push_right_in);
			} else {
				isOpenModel = false;
				ll_layout.setVisibility(View.GONE);
				rl_main.setVisibility(View.VISIBLE);
				tv_select_model.setText("模式");
//				 getActivity().overridePendingTransition(R.anim.push_right_in,
//						 R.anim.push_right_out);
			}

			break;
		case R.id.tv_listen_order: // 听单，中间按钮
			int isopen = mShared1.getInt("isopen", 1);
			if (isopen != 1) {
				ToastView toastView = new ToastView(getActivity(), "该城市未开通服务");
				toastView.setDuration(5000);
				toastView.show();
				return;
			}
			// 如果不处于出车状态
			if (!isWork) {// 判断出车状态
				// 开启出车状态
				isWork = true;
				// 开启订单动画
				stateAction();
				tv_select_model.setVisibility(View.VISIBLE);
				tv_back_car.setVisibility(View.VISIBLE);
				Log.i("极光开启", "极光开启");
				// 启用极光推送
				// JPushInterface.resumePush(getActivity());
				// //判断上一次的订单是否清除完毕，否则
			}
			if (isHasOrder) {// 判断是否有订单，如果有订单
				// 清楚听单动画，处于抢单状态

				if (isfinsh == 0) {
					Toast.makeText(getActivity(), "您有订单没有确认支付,无法接单", 2000)
							.show();
					// 跳到订单界面
				} else if (isfinsh == 1) {
					String lowest = mShared1.getString("lowest", "0");
					if (lowest != null && balance != null) {
						if (Float.parseFloat(lowest) <= Float.parseFloat(balance)
								) {
							mOrderInfoModel.accept(orderId);
						} else {
							Toast.makeText(getActivity(),
									"余额低于" + lowest + ",请充值", 2000).show();
						}
					} else {
						Toast.makeText(getActivity(), "数据错误,请重新操作", 2000)
								.show();
					}

				} else {
					Toast.makeText(getActivity(), "网络错误，请下拉更新状态", 2000).show();
				}

			} else {
				// 若没有订单，继续听单
				stateAction();
				// 变为接单状态
				isAccept = true;
				// 状态为第一次接单的状态
			}
			break;

		case R.id.tv_back_car:// 收车
			ll_layout.setVisibility(View.GONE);
			rl_main.setVisibility(View.VISIBLE);
			Log.i("极光停止", "极光停止");
			// 点击收车的时候，停止接受推送订单
			clearOrder();
			// 无订单
			isHasOrder = false;
			// isForeground = false;
			// 不接受订单
			isAccept = false;
			// 不是第一次接受订单
			// isFirstAccept = false;
			// 如果处于工作状态

			if (isWork) {
				// 设置它不处于工作状态
				isWork = false;
				// 设置刷新和收车不可见。清除动画，设置为出车
				// showOut();
			}
			showOut();
			break;

		default:
			break;
		}
	}


	/**
	 * 收车
	 */
	private void showOut() {
		tv_select_model.setVisibility(View.INVISIBLE);
		tv_back_car.setVisibility(View.INVISIBLE);
		iv_listen_order.clearAnimation();
		iv_listen_order.setBackgroundResource(R.drawable.icon_a0_work);
		tv_listen_order.setText("出车");

	}

	/**
	 * 跳转到订单详情界面
	 */
	private void startEnterOrderActivity() {
		Intent intent = new Intent(getActivity(), D1_OrderActivity.class);
		intent.putExtra(D1_OrderActivity.ORDER_ID, orderId);
		startActivity(intent);
		getActivity().overridePendingTransition(R.anim.push_right_in,
				R.anim.push_right_out);

	}

	/**
	 * 注册消息监听
	 */
	public void registerMessageReceiver() {

		// if (orderCount <= 1) {
		mMessageReceiver = new MessageReceiver();
		IntentFilter filter = new IntentFilter();
		filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
		filter.addAction(MESSAGE_RECEIVED_ACTION);
		getActivity().registerReceiver(mMessageReceiver, filter);
		// }

	}

	public class MessageReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			System.out.println("广播收到自定义消息");

			if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {

				messge = intent.getStringExtra(KEY_MESSAGE);

				if (isAccept) {// 当可以接单的时候
					getJpullMsg(); // 获得订单号以及订单
					isAccept = false;
					// 接收到推送的订单
					isHasOrder = true;
				} else {// 正在接单的时候那么就保存三个订单的id
					System.out.println("前面的单正在处理，先保存订单");
					System.out.println("listId.size()" + listId.size());
					if (listId.size() > 3) {
						return;
					} else {
						JSONObject obj;
						try {
							System.out.println("message" + messge);
							obj = new JSONObject(messge);
							mOrderId = obj.getString("order_id");
							System.out.println("mOrderId" + mOrderId);

							listId.add(mOrderId);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}

//				StringBuilder showMsg = new StringBuilder();
//				showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
//
//				Toast.makeText(getActivity(), showMsg.toString(),
//						Toast.LENGTH_SHORT).show();

			}
		}
		// 显示准备接单的状态

	}

	private void showOrderState() {
		isHasOrder = true;
		System.out.println("有单可以抢");
		iv_listen_order.clearAnimation();
		iv_listen_order.setBackgroundResource(R.drawable.listen_order);
		tv_listen_order.setText("抢单");
		tv_select_model.setVisibility(View.VISIBLE);
		tv_back_car.setVisibility(View.VISIBLE);

	}

	@Override
	public void OnMessageResponse(String url, JSONObject jo, AjaxStatus status)
			throws JSONException {
		if (url.endsWith(ApiInterface.USER_BALANCE)) {
			mBalance.setVisibility(View.VISIBLE);
			mBalance.setText(Utils.formatBalance(mUserBalance.publicBalance)
					+ getString(R.string.yuan));
			balance = Utils.formatBalance(mUserBalance.publicBalance);
		} else if (url.endsWith(ApiInterface.USER_PROFILE_DRIVER)) {

			userprofileResponse response = new userprofileResponse();
			response.fromJson(jo);
			mUser = response.user;
			mImageLoader.displayImage(mUser.avatar.thumb, mAvarta,
					O2OMobile.options_head);
			if (!mUser.count.equals("") && mUser.count != null) {
				mOrderNum.setText(mUser.count);
			}
			if (!mUser.allcount.equals("") && mUser.allcount != null) {
				mOrder_finish_rate.setText(mUser.allcount + "%");
			}

			System.out.println("订单数" + mUser.count);
			if (!mUser.nickname.equals("") && mUser.nickname != null) {
				mName.setText(mUser.nickname);
			}
			if (!mUser.comment_goodrate.equals("")
					&& mUser.comment_goodrate != null) {
				mCommentGoodRate.setText((int) (Double
						.parseDouble(mUser.comment_goodrate) * 100) + "%");
				Log.i("goodrate",
						(int) (Double.parseDouble(mUser.comment_goodrate) * 100)
								+ "%");
			}
			if (!mUser.comment_goodrate.equals("")
					&& mUser.comment_goodrate != null) {
				Float rank = Float.parseFloat(mUser.comment_goodrate) * 5;
				System.out.println("rank" + rank);
				int ranks = new BigDecimal(rank).setScale(0,
						BigDecimal.ROUND_HALF_UP).intValue();
				System.out.println("ranks" + ranks);
				for (int i = 0; i < ranks; i++) {
					ImageView starImage = starList.get(i);
					starImage.setImageResource(R.drawable.b7_star_on);
				}

				for (int i = ranks; i < starList.size(); i++) {
					ImageView starImage = starList.get(i);
					starImage.setImageResource(R.drawable.b7_star_off);
				}
				starList.clear();
				// }
			}
		} else if (url.endsWith(ApiInterface.ORDER_INFO)) {

			if (mOrderInfoModel.publicOrder != null) {// 显示订单
				ly_jpull_order.setVisibility(View.VISIBLE);
				switch (receiveType) {
				case 1:// 实时订单
					if (mOrderInfoModel.publicOrder.service_type == 1) {
						loadVoiceAndVibrator();
						showOrderState();// 显示准备接单的状态
						a1_img_type
								.setImageResource(R.drawable.order_fragment_type_instant);
					} else {
						clearOrder();
					}
					break;
				case 2:// 预约订单,
					if (mOrderInfoModel.publicOrder.service_type == 2) {
						loadVoiceAndVibrator();
						showOrderState();// 显示准备接单的状态
						a1_img_type
								.setImageResource(R.drawable.order_fragment_type_preorder);
					} else {
						clearOrder();
					}
					break;

				case 3:// 全部订单
						// ly_jpull_order.setVisibility(View.VISIBLE);
					loadVoiceAndVibrator();
					showOrderState();// 显示准备接单的状态
					if (mOrderInfoModel.publicOrder.service_type == 2) {
						a1_img_type
								.setImageResource(R.drawable.order_fragment_type_preorder);
					} else {
						a1_img_type
								.setImageResource(R.drawable.order_fragment_type_instant);
					}
					break;
				case 4:// 全部不接受订单
					clearOrder();
					break;
				case 5:// 清除实时订单
						// 清除实时订单
					if (mOrderInfoModel.publicOrder.service_type == 1) {
						clearOrder();
					}
					break;
				case 6:// 清除预约订单
					if (mOrderInfoModel.publicOrder.service_type == 2) {
						clearOrder();
					}
					break;
				}
				if (mOrderInfoModel.publicOrder.location.name != null) {
					tv_start.setText(mOrderInfoModel.publicOrder.location.name);
				}
				if (mOrderInfoModel.publicOrder.location.name_end != null) {
					tv_end.setText(mOrderInfoModel.publicOrder.location.name_end);
				}
				if (mOrderInfoModel.publicOrder.created_at != null) {
					tv_create_time.setText(TimeUtil
							.timeAgo(mOrderInfoModel.publicOrder.created_at));
				}
				if (mOrderInfoModel.publicOrder.offer_price != null) {
					mPrice.setText(mOrderInfoModel.publicOrder.offer_price);
				}
				Log.i("订单状态", mOrderInfoModel.publicOrder.order_status + "");
				orderId = mOrderInfoModel.publicOrder.id;
				System.out.println("publicOrder.id"
						+ mOrderInfoModel.publicOrder.id);
				System.out.println("orderId" + orderId);

//				showOrderState();// 显示准备接单的状态
			}

			/**
			 * mOrderInfoModel.publicOrder.order_status 订单状态 0; //客户发单 1;
			 * //已确认接单 2;//工作完成 3; //已付款 4; //付款已确认 5; //雇员已评价 const
			 * OS_EMPLOYER_COMMENTED = 6; //雇主已评价 const OS_FINISHED = 7; //订单结束
			 * const OS_CANCELED = 8; //订单取消
			 */
		} else if (url.endsWith(ApiInterface.ORDER_ACCEPT)) {

			orderacceptResponse response = new orderacceptResponse();
			response.fromJson(jo);
			if (response.succeed == 1) {// 接单成功
				isAccept = false;
				// showOrderDialog(true, response);
				ToastView toastView = new ToastView(getActivity(), "恭喜，您已接单！");
				toastView.setGravity(Gravity.CENTER, 0, 0);
				toastView.show();

				startEnterOrderActivity();

			} else {// 接单失败
				ToastView toastView = new ToastView(getActivity(), "订单已被抢！");
				toastView.setGravity(Gravity.CENTER, 0, 0);
				toastView.show();
				loadSaveOrder();
			}

		} else if (url.endsWith(ApiInterface.ORDERLIST_ISACCEPT)) {
			orderlistpublishedResponse response = new orderlistpublishedResponse();
			response.fromJson(jo);
			if (response.succeed == 1) {//
//				Toast.makeText(getActivity(), "接单" + isfinsh, 2000).show();
				if (response.count > 0) {// 不可以接单
					isfinsh = 0;
					Toast.makeText(getActivity(), "您有订单没有确认支付,无法接单", 2000)
							.show();

				} else {
					isfinsh = 1;
//					Toast.makeText(getActivity(), "接单" + isfinsh, 2000).show();
				}

			}
		}
	}

	/**
	 * 加载保存的订单
	 */
	private void loadSaveOrder() {
		System.out.println("加载旧订单,清单，或者听单");
		clearOrder();
		if (isHasOrder) {// 如果有推送过来新的订单

		} else {// 没有的话就加载存有的订单
			if (ly_jpull_order.getVisibility() != View.VISIBLE) {// 如果已经有订单显示
																	// 就不加载了
																	// 没有才加载
				System.out.println("MyReceiver.listId" + listId);
				if (listId != null && listId.size() > 0) {
					if (isNum(listId.get(0))) {
						System.out.println("MyReceiver.listId" + listId.get(0));
						mOrderInfoModel.get(Integer.parseInt(listId.get(0)));
						listId.remove(0);

					}
				}
			}
		}
	}

	// 清除订单
	private void clearOrder() {
		// TODO Auto-generated method stub
		// 订单付款确认之后，清除推送的数据
		mOrderId = null;
//		if (!"".equals(mOrderInfoModel)) {
//			if (!"".equals(mOrderInfoModel.publicOrder)) {
//				mOrderInfoModel.publicOrder.clear();
//			}
//		}
//		System.out.println("mOrderInfoModel的值：=="+mOrderInfoModel);
//		System.out.println("mOrderInfoModel.publicOrder的值：=="+mOrderInfoModel.publicOrder);
		if (mOrderInfoModel != null) {
			if (mOrderInfoModel.publicOrder != null) {
				mOrderInfoModel.publicOrder.clear();
			}
		}
		isHasOrder = false;
		isAccept = true;
		tv_start.setText("");
		tv_end.setText("");
		tv_create_time.setText("");
		mPrice.setText("");
		Log.i("aaaaaaaaaaaaa", "数据被清除");
		ly_jpull_order.setVisibility(View.INVISIBLE);
		tv_select_model.setVisibility(View.VISIBLE);
		tv_back_car.setVisibility(View.VISIBLE);
		stateAction();
	}

	// 判断字符串是否为数字
	public static boolean isNum(String str) {

		try {
			new BigDecimal(str);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	// 获取推送消息
	public void getJpullMsg() {
		try {
			JSONObject obj = new JSONObject(messge);
			if (ly_jpull_order.getVisibility() != View.VISIBLE) {
				mOrderId = obj.getString("order_id");
				Log.i("orderId", mOrderId);
				if (isNum(mOrderId)) {
					System.out.println("有单可以接");
					orderId = Integer.valueOf(mOrderId);
					mOrderInfoModel = new OrderInfoModel(getActivity());
					mOrderInfoModel.addResponseListener(this);
					mOrderInfoModel.get(orderId);
				}
			} else {
				System.out.println("前面有单在处理");
			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 极光推送设置别名
	private static final int MSG_SET_ALIAS = 1001;

	private void setAlias(String alias) {
		System.out.println("设置别名");
		if (TextUtils.isEmpty(alias)) {
			return;
		}
		if (!ExampleUtil.isValidTagAndAlias(alias)) {

			return;
		}
		mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
	}

	private final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case MSG_SET_ALIAS:
				if(getActivity()!=null){
					JPushInterface.setAliasAndTags(getActivity().getApplicationContext(), (String) msg.obj,
							null, mAliasCallback);
				}
				
				break;
			default:
			}
		}
	};
	private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

		@Override
		public void gotResult(int code, String alias, Set<String> tags) {
			String logs;
			switch (code) {
			case 0:
				mEditor.putBoolean("isjpush", true);
				mEditor.commit();
				System.out.println("极光推送绑定成功");
				break;

			case 6002:
				logs = "Failed to set alias and tags due to timeout. Try again after 6s.";
				System.out.println("logs" + logs);
				if (getActivity()!=null) {
					if (ExampleUtil.isConnected(getActivity())) {
						mHandler.sendMessageDelayed(
								mHandler.obtainMessage(MSG_SET_ALIAS, alias),
								1000 * 6);
					} else {
					}
				}
				break;

			default:
				logs = "Failed with errorCode = " + code;

			}

		}
	};
	private Editor editor;
	private MediaPlayer player;
	private Vibrator vibrator;

	public void onEvent(Object event) {
		Message message = (Message) event;
		if (message.what == MessageConstant.SIGN_IN_DRIVER) {

		}
	}

	@Override
	public void onRefresh(int id) {
		mUserBalance.getProfile_driver();
		orderModel.isAccept();// 判断司机是否可以接单
		mUserBalance.get();
		LocationManager.getInstance().refreshLocation();

	}

	@Override
	public void onLoadMore(int id) {
		// TODO Auto-generated method stub

	}
	/**
	 * 播放声音并开启震动
	 */
	private void loadVoiceAndVibrator() {
		// // 接受到推送的消息，播放声音
		player.start();
		// 开启震动
		long[] pattern = { 100, 400, 100, 400 }; // 停止 开启 停止 开启
		vibrator.vibrate(pattern, -1); // 只震动一次，index设为-1
	}

}
